package com.sz.app.edi.job.rpt;

import com.sz.biz.common.base.dto.AreaDto;
import com.sz.biz.common.base.entity.Country;
import com.sz.biz.common.base.entity.ExchangeRate;
import com.sz.biz.common.base.service.AreaManager;
import com.sz.biz.common.base.service.ExchangeRateService;
import com.sz.biz.common.customer.dto.CusCompanyDto;
import com.sz.biz.common.customer.entity.CusCustomer;
import com.sz.biz.common.customer.service.CustomerCompanyService;
import com.sz.biz.common.customer.service.CustomerService;
import com.sz.biz.common.sup.entity.Supplier;
import com.sz.biz.common.sup.service.SupplierService;
import com.sz.biz.logistics.billing.dto.QuotationCalcResult;
import com.sz.biz.logistics.billing.service.QuotationCalcService;
import com.sz.biz.logistics.core.entity.Product;
import com.sz.biz.logistics.core.service.ProductService;
import com.sz.biz.logistics.core.service.ServiceService;
import com.sz.biz.logistics.ord.entity.OrdOrderAddress;
import com.sz.biz.logistics.ord.entity.OrdServiceBill;
import com.sz.biz.logistics.ord.service.OrdOrderAddressService;
import com.sz.biz.logistics.ord.service.OrdServiceBillService;
import com.sz.biz.rpt.entity.*;
import com.sz.biz.rpt.service.*;
import com.sz.biz.trade.ord.dto.TrdOrderGoodsRelDto;
import com.sz.biz.trade.ord.entity.TrdOrder;
import com.sz.biz.trade.ord.service.TrdOrderGoodsRelService;
import com.sz.biz.trade.ord.service.TrdOrderService;
import com.sz.common.base.job.JobScheduler;
import com.sz.common.base.logger.Logger;
import com.sz.common.base.utils.DateUtils;
import com.sz.common.base.utils.EntityUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.entity.SysDict;
import com.sz.common.core.system.service.SysDictService;
import com.sz.common.core.system.service.UnitConversionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ExecutionException;

/**
 * Function: //TODO ADD FUNCTION. <br>
 * Date: 2017年12月05日 14:43 <br>
 * Author: wentao.chang
 */
@Service("saleRptJobScheduler")
public class SaleRptJobSchedulerImpl implements JobScheduler {

    private Logger logger = Logger.getLogger(this.getClass());

    private final static String CNY = "CNY";
    private final static String CN = "CN";
    private final static String T = "t";
    private final static int LOGISTICS = 1;
    private final static int TRD = 2;
    private final static int LOGISTICS_OR_TRD = 3;

    @Autowired
    private RptSaleSummaryService rptSaleSummaryService;

    @Autowired
    private RptSaleProductService rptSaleProductService;

    @Autowired
    private RptSaleSupplierService rptSaleSupplierService;

    @Autowired
    private RptSaleCustomerService rptSaleCustomerService;

    @Autowired
    private RptSaleAreaService rptSaleAreaService;

    @Autowired
    private RptCalcJobService rptCalcJobService;

    @Autowired
    private OrdServiceBillService ordServiceBillService;

    @Autowired
    private ExchangeRateService exchangeRateService;

    @Autowired
    private ProductService productService;

    @Autowired
    private QuotationCalcService calcService;

    @Autowired
    private UnitConversionService unitConversionService;

    @Autowired
    private ServiceService serviceService;

    @Autowired
    private SupplierService supplierService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerCompanyService customerCompanyService;

    @Autowired
    private OrdOrderAddressService ordOrderAddressService;
    @Autowired
    private AreaManager areaManager;

    @Autowired
    private TrdOrderService trdOrderService;

    @Autowired
    private TrdOrderGoodsRelService trdOrderGoodsRelService;

    @Autowired
    private SysDictService sysDictService;

    @Override
    public void execute() throws ExecutionException, InterruptedException, ParseException {
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.YEAR, -1);
        String todayStr = DateUtils.formatSimpleDate(new Date());
        String indexDayStr = DateUtils.formatSimpleDate(calendar.getTime());
        //检查历史的数据，可从数据库删除后检测重新生成
        while (indexDayStr.compareTo(todayStr) < 0) {
            Date date = DateUtils.getDayBegin(calendar.getTime());
            RptCalcJob rcc = rptCalcJobService.findByDate(date);
            if (rcc == null) {
                logger.info("-------->汇总" + DateUtils.formatDetailDate(date) + "的报表数据");
                calcDateRpt(date);
            }
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            indexDayStr = DateUtils.formatSimpleDate(calendar.getTime());
        }
        //当天的数据
        rptCalcJobService.deleteByDate(DateUtils.getDayBegin(new Date()));
        logger.info("-------->汇总" + todayStr + "的报表数据");
        calcDateRpt(new Date());
    }

    public void calcDateRpt(Date date) throws ParseException {
        List<SysDict> weights = sysDictService.findByCatalog("sys.unit.weight");
        Map<String, SysDict> weightMap = EntityUtils.getStringKeyMapFromBeans(weights, "code");

        RptCalcJob job = new RptCalcJob();
        job.setStartTime(new Date());

        Date dateBegin = DateUtils.getDayBegin(date);
        Date dateEnd = DateUtils.getDayEnd(date);
        List<OrdServiceBill> ords = ordServiceBillService.findByDate(2, dateBegin, dateEnd);
        Map<String, OrdOrderAddress> orderNoMap = new HashMap<>(16);
        Map<String, BigDecimal> orderFeeWeightMap = new HashMap<>(16);
        Map<String, String> supplierOrderMap = new HashMap<>(16);

        RptSaleSummary rptSaleSummary = new RptSaleSummary();
        //key = type+productId
        Map<String, RptSaleProduct> rptSaleProductMap = new HashMap<>(16);
        //key = type+supplierId
        Map<String, RptSaleSupplier> rptSaleSupplierMap = new HashMap<>(16);
        //key = type+customerId
        Map<String, RptSaleCustomer> rptSaleCustomerMap = new HashMap<>(16);
        //key = type+countryId+cityId
        Map<String, RptSaleArea> rptSaleAreaMap = new HashMap<>(16);

        BigDecimal summaryAmount = BigDecimal.ZERO;
        BigDecimal summaryVolume = BigDecimal.ZERO;

        for (OrdServiceBill osb : ords) {
            BigDecimal orderAmount = BigDecimal.ZERO;
            BigDecimal orderFeeWeight = BigDecimal.ZERO;

            OrdOrderAddress orderAddress;
            if (CNY.equals(osb.getCurrencyCode())) {
                orderAmount = osb.getAmountDue();
            } else if (CNY.equals(osb.getCustCurrencyCode())) {
                orderAmount = osb.getCustCurrencyAmount();
            } else {
                //获取汇率
                ExchangeRate exchangeRate = exchangeRateService.findCurrencyRoeByDate(osb.getCurrencyCode(), CNY,
                        osb.getBillTime());
                if (exchangeRate != null) {
                    orderAmount = osb.getAmountDue().multiply(exchangeRate.getRate());
                }
            }
            summaryAmount = summaryAmount.add(orderAmount);

            if (!orderNoMap.containsKey(osb.getOrderNo())) {
                QuotationCalcResult result = calcService.calcWaybillFeeWeight(osb.getOrderNo());
                if (!ObjectUtils.isEmpty(result)) {
                    try {
                        orderFeeWeight = unitConversionService.getTargetWeight(result.getFeeWeight(),
                                result.getFeeWeightUnitCode(), T);
                        summaryVolume = summaryVolume.add(orderFeeWeight);
                    } catch (Exception e) {
                        //do nothing
                    }
                }
                orderAddress = ordOrderAddressService.findByOrderNo(osb.getOrderNo());
                orderFeeWeightMap.put(osb.getOrderNo(), orderFeeWeight);
            } else {
                orderAddress = orderNoMap.get(osb.getOrderNo());
                orderFeeWeight = orderFeeWeightMap.get(osb.getOrderNo());
            }

            //产品
            String productKey = LOGISTICS + "" + osb.getProductId();
            if (!rptSaleProductMap.containsKey(productKey)) {
                Product product = productService.findShortById(osb.getProductId());
                RptSaleProduct temp = new RptSaleProduct();
                temp.setBizDate(dateBegin);
                temp.setProductId(osb.getProductId());
                temp.setProductName(product.getName());
                temp.setType(LOGISTICS);
                temp.setWeek(getWeekByDate(dateBegin));
                temp.setYear(getYearByDate(dateBegin));
                temp.setMonth(getMonthByDate(dateBegin));
                temp.setQuarter(getQuarterByDate(dateBegin));
                rptSaleProductMap.put(productKey, temp);
            }
            RptSaleProduct rptSaleProduct = rptSaleProductMap.get(productKey);
            //服务的费用单中是按单个服务计费的,所以每笔都要记
            rptSaleProduct.setAmount(rptSaleProduct.getAmount().add(orderAmount));
            //一单只有一个订单重量 订单数
            if (!orderNoMap.containsKey(osb.getOrderNo())) {
                rptSaleProduct.setVolume(rptSaleProduct.getVolume().add(orderFeeWeight));
                rptSaleProduct.setBillCount(rptSaleProduct.getBillCount() + 1);
            }


            //供应商
            String supplierKey = LOGISTICS + "" + osb.getServiceId();
            if (!rptSaleSupplierMap.containsKey(supplierKey)) {
                com.sz.biz.logistics.core.entity.Service svc = serviceService.findById(osb.getServiceId());
                RptSaleSupplier temp = new RptSaleSupplier();
                temp.setBizDate(dateBegin);
                temp.setSupplierId(svc.getSupplierId());
                temp.setWeek(getWeekByDate(dateBegin));
                temp.setYear(getYearByDate(dateBegin));
                temp.setMonth(getMonthByDate(dateBegin));
                temp.setQuarter(getQuarterByDate(dateBegin));

                Supplier supplier = supplierService.findSimpleById(svc.getSupplierId());
                if (supplier != null) {
                    temp.setSupplierName(supplier.getName());
                }
                temp.setType(LOGISTICS);
                rptSaleSupplierMap.put(supplierKey, temp);
            }
            RptSaleSupplier rptSaleSupplier = rptSaleSupplierMap.get(supplierKey);
            //服务的费用单中是按单个服务计费的,所以每笔都要记
            rptSaleSupplier.setAmount(rptSaleSupplier.getAmount().add(orderAmount));
            //一个供应商一单只有一个订单重量 订单数
            if (!supplierOrderMap.containsKey(supplierKey + osb.getOrderNo())) {
                rptSaleSupplier.setVolume(rptSaleSupplier.getVolume().add(orderFeeWeight));
                rptSaleSupplier.setBillCount(rptSaleSupplier.getBillCount() + 1);
                supplierOrderMap.put(supplierKey + osb.getOrderNo(), "");
            }

            //客户
            String customerKey = LOGISTICS + "" + osb.getCustomerId();
            if (!rptSaleCustomerMap.containsKey(customerKey)) {
                CusCustomer customer = customerService.findShortById(osb.getCustomerId());
                RptSaleCustomer temp = new RptSaleCustomer();
                temp.setBizDate(dateBegin);
                temp.setCustomerId(customer.getId());
                temp.setCustomerName(customer.getUserName());
                temp.setType(LOGISTICS);
                temp.setWeek(getWeekByDate(dateBegin));
                temp.setYear(getYearByDate(dateBegin));
                temp.setMonth(getMonthByDate(dateBegin));
                temp.setQuarter(getQuarterByDate(dateBegin));
                rptSaleCustomerMap.put(customerKey, temp);
            }
            RptSaleCustomer rptSaleCustomer = rptSaleCustomerMap.get(customerKey);
            rptSaleCustomer.setAmount(rptSaleCustomer.getAmount().add(orderAmount));
            //一单只有一个订单重量 订单数
            if (!orderNoMap.containsKey(osb.getOrderNo())) {
                rptSaleCustomer.setVolume(rptSaleCustomer.getVolume().add(orderFeeWeight));
                rptSaleCustomer.setBillCount(rptSaleCustomer.getBillCount() + 1);
            }


            //地区
            String toCountry = orderAddress.getToCountry();
            String toProvince = orderAddress.getToProvince();
            String toCity = orderAddress.getToCity();
            String areaKey = LOGISTICS + orderAddress.getToCountry() + orderAddress.getToCity();
            if (!rptSaleAreaMap.containsKey(areaKey)) {
                RptSaleArea temp = new RptSaleArea();
                temp.setBizDate(dateBegin);
                temp.setCountryId(toCountry);
                Country country = areaManager.findByCountryCode(toCountry);
                temp.setCountryName(country.getName());
                //省
                if (!StringUtils.isEmpty(toProvince)) {
                    List<AreaDto> areas = areaManager.findByAreaId(CN, toProvince);
                    temp.setProvinceId(toProvince);
                    if (!CollectionUtils.isEmpty(areas)) {
                        temp.setProvinceName(areas.get(0).getName());
                    }
                }
                //市
                if (!StringUtils.isEmpty(toCity)) {
                    List<AreaDto> areas = areaManager.findByAreaId(orderAddress.getToCountry(), toCity);
                    temp.setCityId(toCity);
                    if (!CollectionUtils.isEmpty(areas)) {
                        temp.setCityName(areas.get(0).getName());
                    }
                }
                temp.setType(LOGISTICS);
                temp.setWeek(getWeekByDate(dateBegin));
                temp.setYear(getYearByDate(dateBegin));
                temp.setMonth(getMonthByDate(dateBegin));
                temp.setQuarter(getQuarterByDate(dateBegin));
                rptSaleAreaMap.put(areaKey, temp);
            }
            RptSaleArea rptSaleArea = rptSaleAreaMap.get(areaKey);
            rptSaleArea.setAmount(rptSaleArea.getAmount().add(orderAmount));
            //一单只有一个订单重量 订单数
            if (!orderNoMap.containsKey(osb.getOrderNo())) {
                rptSaleArea.setVolume(rptSaleArea.getVolume().add(orderFeeWeight));
                rptSaleArea.setBillCount(rptSaleArea.getBillCount() + 1);
            }

            orderNoMap.put(osb.getOrderNo(), orderAddress);
        }
        rptSaleSummary.setBizDate(dateBegin);

        rptSaleSummary.setWeek(getWeekByDate(dateBegin));
        rptSaleSummary.setYear(getYearByDate(dateBegin));
        rptSaleSummary.setMonth(getMonthByDate(dateBegin));
        rptSaleSummary.setQuarter(getQuarterByDate(dateBegin));
        rptSaleSummary.setLogisticsAmount(summaryAmount);
        rptSaleSummary.setLogisticsVolume(summaryVolume);
        rptSaleSummary.setLogisticsBillCount(orderNoMap.keySet().size());

        //客户
        List<CusCustomer> cusCustomerlist = customerService.finByCreateTimeForRpt(dateBegin, dateEnd);
        if (!CollectionUtils.isEmpty(cusCustomerlist)) {
            for (CusCustomer cusCustomer : cusCustomerlist) {
                if (cusCustomer.getUserType() == TRD) {
                    rptSaleSummary.setTradeNewCustCount(rptSaleSummary.getTradeNewCustCount() + 1);
                }
                if (cusCustomer.getUserType() == LOGISTICS) {
                    rptSaleSummary.setLogisticsNewCustCount(rptSaleSummary.getLogisticsNewCustCount() + 1);
                }
                if (cusCustomer.getUserType() == LOGISTICS_OR_TRD) {
                    rptSaleSummary.setTradeNewCustCount(rptSaleSummary.getTradeNewCustCount() + 1);
                    rptSaleSummary.setLogisticsNewCustCount(rptSaleSummary.getLogisticsNewCustCount() + 1);
                }
            }
        }
        //供应商
        List<Supplier> supplierlist = supplierService.finByCreateTimeForRpt(dateBegin, dateEnd);
        if (!CollectionUtils.isEmpty(supplierlist)) {
            for (Supplier supplier : supplierlist) {
                if (supplier.getType() == TRD) {
                    rptSaleSummary.setTradeNewSupCount(rptSaleSummary.getTradeNewSupCount() + 1);
                } else {
                    rptSaleSummary.setLogisticsNewSupCount(rptSaleSummary.getLogisticsNewSupCount() + 1);
                }
            }
        }

        //贸易采购订单
        List<TrdOrder> trdPurOrders = trdOrderService.findPurByReceiptTimeForRpt(dateBegin, dateEnd);
        if (!CollectionUtils.isEmpty(trdPurOrders)) {
            for (TrdOrder trdOrder : trdPurOrders) {
                Supplier supplier = supplierService.findSimpleById(trdOrder.getSellerId());

                //供应商
                String supplierKey = TRD + "" + trdOrder.getSellerId();
                if (!rptSaleSupplierMap.containsKey(supplierKey)) {
                    RptSaleSupplier temp = new RptSaleSupplier();
                    temp.setBizDate(dateBegin);
                    temp.setSupplierId(trdOrder.getSellerId());
                    temp.setWeek(getWeekByDate(dateBegin));
                    temp.setYear(getYearByDate(dateBegin));
                    temp.setMonth(getMonthByDate(dateBegin));
                    temp.setQuarter(getQuarterByDate(dateBegin));
                    if (supplier != null) {
                        temp.setSupplierName(supplier.getName());
                    }
                    temp.setType(TRD);
                    rptSaleSupplierMap.put(supplierKey, temp);
                }
                RptSaleSupplier rptSaleSupplier = rptSaleSupplierMap.get(supplierKey);
                rptSaleSupplier.setBillCount(rptSaleSupplier.getBillCount() + 1);

                List<TrdOrderGoodsRelDto> trdGoods = trdOrderGoodsRelService.findByOrderNo(trdOrder.getOrderNo(), 1);

                if (!CollectionUtils.isEmpty(trdGoods)) {
                    for (TrdOrderGoodsRelDto goodsRelDto : trdGoods) {
                        //每个商品都算作此供应商的一个金额
                        if (goodsRelDto.getAmountDue() == null) {
                            continue;
                        }
                        rptSaleSupplier.setAmount(rptSaleSupplier.getAmount().add(goodsRelDto.getAmountDue()));
                        if (weightMap.get(goodsRelDto.getGoodsUnit()) != null) {
                            BigDecimal volume = BigDecimal.ZERO;
                            try {
                                volume = unitConversionService.getTargetWeight(goodsRelDto.getGoodsNum(), goodsRelDto.getGoodsUnit(), T);
                            } catch (Exception e) {
                                //do nothing
                            }
                            rptSaleSupplier.setVolume(rptSaleSupplier.getVolume().add(volume));
                        }
                    }
                }
            }
        }

        Map<String, String> trdOrderNoMap = new HashMap<>(16);
        BigDecimal summaryTrdAmount = BigDecimal.ZERO;
        BigDecimal summaryTrdVolume = BigDecimal.ZERO;
        //贸易销售订单
        List<TrdOrder> trdOrders = trdOrderService.findSaleByReceiptTimeForRpt(dateBegin, dateEnd);
        if (!CollectionUtils.isEmpty(trdOrders)) {
            for (TrdOrder trdOrder : trdOrders) {
                //增值税
                BigDecimal vat = trdOrder.getVat() == null ? BigDecimal.ZERO : trdOrder.getVat();
                if (!CNY.equals(trdOrder.getCurrencyCode())) {
                    //获取汇率
                    ExchangeRate exchangeRate = exchangeRateService.findCurrencyRoeByDate(
                            trdOrder.getCurrencyCode(), CNY, trdOrder.getReceiptTime());
                    if (exchangeRate != null) {
                        vat = vat.multiply(exchangeRate.getRate());
                    }
                }
                if (vat != null) {
                    summaryTrdAmount = summaryTrdAmount.add(vat);
                }

                CusCompanyDto cusCompanyDto = customerCompanyService.findCompanyByCustomerId(trdOrder.getCustomerId());

                //客户
                String customerKey = TRD + "" + trdOrder.getCustomerId();
                if (!rptSaleCustomerMap.containsKey(customerKey)) {
                    CusCustomer customer = customerService.findShortById(trdOrder.getCustomerId());
                    RptSaleCustomer temp = new RptSaleCustomer();
                    temp.setBizDate(dateBegin);
                    temp.setCustomerName(customer.getUserName());
                    temp.setCustomerId(customer.getId());
                    temp.setType(TRD);
                    temp.setWeek(getWeekByDate(dateBegin));
                    temp.setYear(getYearByDate(dateBegin));
                    temp.setMonth(getMonthByDate(dateBegin));
                    temp.setQuarter(getQuarterByDate(dateBegin));
                    rptSaleCustomerMap.put(customerKey, temp);
                }
                RptSaleCustomer rptSaleCustomer = rptSaleCustomerMap.get(customerKey);
                rptSaleCustomer.setBillCount(rptSaleCustomer.getBillCount() + 1);

                //地区
                RptSaleArea rptSaleArea = null;
                if (cusCompanyDto != null) {
                    String toCountry = cusCompanyDto.getLocationCountryCode();
                    String toCity = cusCompanyDto.getLocationCityCode();
                    String areaKey = TRD + toCountry + toCity;
                    if (!rptSaleAreaMap.containsKey(areaKey)) {
                        RptSaleArea temp = new RptSaleArea();
                        temp.setBizDate(dateBegin);
                        temp.setCountryId(toCountry);
                        Country country = areaManager.findByCountryCode(toCountry);
                        if (country != null) {
                            temp.setCountryName(country.getName());
                        }
                        //省
                        //if (!StringUtils.isEmpty(toProvince)) {
                        ///    List<AreaDto> areas = areaManager.findByAreaId(CN, toProvince);
                        //    temp.setProvinceId(toProvince);
                        //    temp.setProvinceName(areas.get(0).getName());
                        //}
                        //市
                        temp.setCityId(toCity);
                        if (!StringUtils.isEmpty(toCity)) {
                            List<AreaDto> areas = areaManager.findByAreaId(toCountry, toCity);
                            if (!CollectionUtils.isEmpty(areas)) {
                                temp.setCityName(areas.get(0).getName());
                            }
                        }
                        temp.setType(TRD);
                        temp.setWeek(getWeekByDate(dateBegin));
                        temp.setYear(getYearByDate(dateBegin));
                        temp.setMonth(getMonthByDate(dateBegin));
                        temp.setQuarter(getQuarterByDate(dateBegin));
                        rptSaleAreaMap.put(areaKey, temp);
                    }
                    rptSaleArea = rptSaleAreaMap.get(areaKey);
                }
                List<TrdOrderGoodsRelDto> trdGoods = trdOrderGoodsRelService.findByOrderNo(trdOrder.getOrderNo(), 1);
                if (!CollectionUtils.isEmpty(trdGoods)) {
                    for (TrdOrderGoodsRelDto goodsRelDto : trdGoods) {
                        BigDecimal volume = BigDecimal.ZERO;
                        if (weightMap.get(goodsRelDto.getGoodsUnit()) != null) {
                            try {
                                volume = unitConversionService.getTargetWeight(goodsRelDto.getGoodsNum(), goodsRelDto.getGoodsUnit(), T);
                            } catch (Exception e) {
                                //do nothing
                            }
                        }

                        BigDecimal amount = BigDecimal.ZERO;
                        if (CNY.equals(goodsRelDto.getGoodsCurrencyType())) {
                            amount = goodsRelDto.getAmountDue();
                        } else {
                            //获取汇率
                            ExchangeRate exchangeRate = exchangeRateService.findCurrencyRoeByDate(
                                    goodsRelDto.getGoodsCurrencyType(), CNY, trdOrder.getReceiptTime());
                            if (exchangeRate != null) {
                                amount = goodsRelDto.getAmountDue().multiply(exchangeRate.getRate());
                            }
                        }
                        if (amount == null) {
                            continue;
                        }

                        //每个商品都算作此客户的一个金额
                        summaryTrdAmount = summaryTrdAmount.add(amount);
                        summaryTrdVolume = summaryTrdVolume.add(volume);

                        //客户
                        rptSaleCustomer.setAmount(rptSaleCustomer.getAmount().add(amount));
                        rptSaleCustomer.setVolume(rptSaleCustomer.getVolume().add(volume));


                        //产品
                        String productKey = TRD + "" + goodsRelDto.getGoodsId();
                        if (!rptSaleProductMap.containsKey(productKey)) {
                            RptSaleProduct temp = new RptSaleProduct();
                            temp.setBizDate(dateBegin);
                            temp.setProductId(goodsRelDto.getGoodsId());
                            temp.setProductName(goodsRelDto.getGoodsName());
                            temp.setType(TRD);
                            temp.setWeek(getWeekByDate(dateBegin));
                            temp.setYear(getYearByDate(dateBegin));
                            temp.setMonth(getMonthByDate(dateBegin));
                            temp.setQuarter(getQuarterByDate(dateBegin));

                            rptSaleProductMap.put(productKey, temp);
                        }
                        RptSaleProduct rptSaleProduct = rptSaleProductMap.get(productKey);
                        rptSaleProduct.setAmount(rptSaleProduct.getAmount().add(amount));
                        //一单只有一个订单重量 订单数
                        if (!trdOrderNoMap.containsKey(goodsRelDto.getOrderNo())) {
                            rptSaleProduct.setVolume(rptSaleProduct.getVolume().add(volume));
                            rptSaleProduct.setBillCount(rptSaleProduct.getBillCount() + 1);
                        }

                        //地区
                        if (rptSaleArea != null) {
                            rptSaleArea.setAmount(rptSaleArea.getAmount().add(amount));
                            rptSaleArea.setVolume(rptSaleArea.getVolume().add(volume));

                            //一单只有一个订单重量 订单数
                            if (!trdOrderNoMap.containsKey(goodsRelDto.getOrderNo())) {
                                rptSaleArea.setBillCount(rptSaleArea.getBillCount() + 1);
                            }

                            trdOrderNoMap.put(trdOrder.getOrderNo(), "");
                        }
                    }
                }
            }
        }

        rptSaleSummary.setTradeAmount(summaryTrdAmount);
        rptSaleSummary.setTradeVolume(summaryTrdVolume);
        rptSaleSummary.setTradeBillCount(trdOrders.size());

        //先删除
        rptSaleAreaService.deleteByDate(dateBegin);
        rptSaleProductService.deleteByDate(dateBegin);
        rptSaleCustomerService.deleteByDate(dateBegin);
        rptSaleSupplierService.deleteByDate(dateBegin);
        rptSaleSummaryService.deleteByDate(dateBegin);
        //保存计算结果
        rptSaleAreaMap.values().forEach(item -> rptSaleAreaService.save(item));
        rptSaleProductMap.values().forEach(item -> rptSaleProductService.save(item));
        rptSaleCustomerMap.values().forEach(item -> rptSaleCustomerService.save(item));
        rptSaleSupplierMap.values().forEach(item -> rptSaleSupplierService.save(item));
        rptSaleSummaryService.save(rptSaleSummary);


        job.setBizDate(dateBegin);
        job.setCalcTime(new Date());
        job.setEndTime(new Date());
        try {
            job.setWorkId(PrincipalUtils.getAccountId());
        } catch (Exception e) {
            job.setWorkId(0);
        }
        rptCalcJobService.save(job);
    }

    private Integer getYearByDate(Date dateBegin) {
        Calendar calendar = new GregorianCalendar();
        calendar.clear();
        calendar.setTime(dateBegin);
        return calendar.get(Calendar.YEAR);
    }

    private Integer getMonthByDate(Date dateBegin) {
        Calendar calendar = new GregorianCalendar();
        calendar.clear();
        calendar.setTime(dateBegin);
        return calendar.get(Calendar.MONTH) + 1;
    }

    private Integer getQuarterByDate(Date dateBegin) {
        Calendar calendar = new GregorianCalendar();
        calendar.clear();
        calendar.setTime(dateBegin);
        return calendar.get(Calendar.MONTH) / 3 + 1;
    }

    private int getWeekByDate(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.clear();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        return calendar.get(Calendar.WEEK_OF_YEAR);
    }

}
